package ruifight.member.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import ruifight.member.dao.AccountRecordMapper;
import ruifight.member.dao.ClassifyInfoMapper;
import ruifight.member.dao.ShopAccountMapper;
import ruifight.member.dao.ShopInfoMapper;
import ruifight.member.dao.TransactionRecordMapper;
import ruifight.member.dao.UserInfoMapper;
import ruifight.member.model.*;
import ruifight.member.service.ShopInfoService;
import ruifight.member.service.UserInfoService;
import ruifight.member.service.base.BaseServiceImplWithBLOBs;
import ruifight.member.util.*;

@Service
public class ShopInfoServiceImpl extends BaseServiceImplWithBLOBs<ShopInfo, ShopInfoExample,ShopInfoWithBLOBs, Long> implements ShopInfoService {

	private static final Logger logger = LoggerFactory.getLogger(ShopInfoServiceImpl.class);

	@Resource
    public ShopInfoMapper shopInfoMapper;
	@Resource
    public UserInfoMapper userInfoMapper;
	@Resource
    public ShopAccountMapper shopAccountMapper;
	@Resource
    public TransactionRecordMapper transactionRecordMapper;
	@Resource
    public ClassifyInfoMapper classifyInfoMapper;
	@Resource
	public AccountRecordMapper accountRecordMapper;
	@Autowired
	public UserInfoService userInfoService;

    public PageInfo<Map<String, Object>> getShopInfoList(int cur_page, int page_size,Map<String, Object> paramMap){
    	PageHelper.startPage(cur_page, page_size);
        List<Map<String, Object>> pageList = shopInfoMapper.getShopInfoList(paramMap);
        int length = pageList.size();
        for(int i = 0;i<length;i++) {
        	String shopType = pageList.get(i).get("shopType").toString();
        	String [] id = shopType.substring(1,shopType.length()-1).replace(" ", "").split(",");
        	System.err.println(id.length);
        	String str = "";
        	for(int num =0;num<id.length;num++) {
        		ClassifyInfo selectByPrimaryKey = classifyInfoMapper.selectByPrimaryKey(Long.parseLong(id[num]));
        		str +=selectByPrimaryKey.getClassifyName()+",";
        	}
        	pageList.get(i).put("shopType", str);
        	Map<String, Object> paramMap2=new HashMap<String, Object>();
        	String shopInfoId = pageList.get(i).get("shopInfoId").toString();
        	paramMap2.put("payeeShopId", Long.parseLong(shopInfoId));
        	Float cumulativeMoney=accountRecordMapper.getCumulativeMoney(paramMap2);
        	pageList.get(i).put("cumulativeMoney", cumulativeMoney);
        }
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(pageList);
        return pageInfo;
    }

	@Override
	public Map<String,Object> addShopInfo(Map<String, Object> paramMap) {
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			ShopInfoWithBLOBs shopInfo = new ShopInfoWithBLOBs();
			shopInfo.setAttr2(paramMap.get("attr2").toString());
			shopInfo.setBusinessPermitPhoto(paramMap.get("businessPermitPhoto").toString());
			shopInfo.setLatitude(paramMap.get("latitude").toString());
			shopInfo.setLongitude(paramMap.get("longitude").toString());
			shopInfo.setTelephone(paramMap.get("telephone").toString());
			shopInfo.setBusinessDate(paramMap.get("businessDate").toString());
			shopInfo.setShopType(paramMap.get("shopType").toString());
			shopInfo.setShopTitle(paramMap.get("shopTitle").toString());
			shopInfo.setShopName(paramMap.get("shopName").toString());
			shopInfo.setShopComment(paramMap.get("shopComment").toString());
			shopInfo.setShopCode(CommonUtil.getUUID());
			shopInfo.setAttr1(paramMap.get("attr1").toString());
			shopInfo.setAttr3(paramMap.get("attr3").toString());
			if(!StringUtils.isEmpty(paramMap.get("headName").toString())) {
				shopInfo.setHeadName(paramMap.get("headName").toString());
			}
			if(!StringUtils.isEmpty(paramMap.get("headPhone").toString())) {
				shopInfo.setHeadPhone(paramMap.get("headPhone").toString());
			}
			shopInfo.setProvince(paramMap.get("province").toString());
			shopInfo.setCity(paramMap.get("city").toString());
			shopInfo.setDistrict(paramMap.get("district").toString());

			UserInfoExample userInfoExample = new UserInfoExample();
			UserInfoExample.Criteria criteria = userInfoExample.createCriteria();
			criteria.andUserStateEqualTo(1);
			criteria.andLoginNameEqualTo(paramMap.get("userPhone").toString());
			UserInfo user = userInfoService.selectOneByExample(userInfoExample);

//			int loginNameCount = userInfoMapper.getLoginNameCount(paramMap.get("userPhone").toString());
			if(ObjUtil.isNotNullAndEmpty(user) && user.getUserType() != 3) {
				map.put("state", 2);
				map.put("msg", "手机号已被注册~");
			}else {
				if (ObjUtil.isNotNullAndEmpty(user)){
					shopInfo.setUserInfoId(user.getUserInfoId());
					shopInfo.setCreateDate(new Date());
					shopInfo.setShopState(1);
					shopInfoMapper.insertSelective(shopInfo);

					ShopAccount sa = new ShopAccount();
					sa.setShopInfoId(shopInfo.getShopInfoId());
					sa.setDiscount(Float.valueOf(paramMap.get("discount").toString()));
					sa.setCreateDate(new Date());
					shopAccountMapper.insertSelective(sa);

					user.setUserType(4);
					userInfoMapper.updateByPrimaryKeySelective(user);
				} else{
					UserInfo ui = new UserInfo();
					ui.setLoginName(shopInfo.getTelephone());
					ui.setPassword(MD5Util.MD5(paramMap.get("certificateCode").toString().substring(12, 18)));
					ui.setMobile(paramMap.get("userPhone").toString());
					ui.setCreateDate(new Date());
					ui.setUserName(paramMap.get("userPhone").toString());
					ui.setUserState(1);
					ui.setCertificateCode(paramMap.get("certificateCode").toString());
					ui.setUserType(2);
					userInfoMapper.insertSelective(ui);

					shopInfo.setUserInfoId(ui.getUserInfoId());
					shopInfo.setCreateDate(new Date());
					shopInfo.setShopState(1);
					shopInfoMapper.insertSelective(shopInfo);

					ShopAccount sa = new ShopAccount();
					sa.setShopInfoId(shopInfo.getShopInfoId());
					sa.setDiscount(Float.valueOf(paramMap.get("discount").toString()));
					sa.setCreateDate(new Date());
					shopAccountMapper.insertSelective(sa);
				}


				map.put("state", 1);
				map.put("msg", "恭喜您注册成功,登录账号："+paramMap.get("userPhone").toString()+",密码："+paramMap.get("certificateCode").toString().substring(12, 18));
			}
		}catch(Exception e) {
			map.put("state", -1);
			map.put("msg", "系统崩溃了,请稍后再尝试~");
			e.printStackTrace();
		}
		return map;
	}



	@Override
	public Map<String, Object> delShopInfo(Long shopInfoId) {
		Map<String,Object> map = new HashMap<String,Object>();
		ShopInfoWithBLOBs selectByPrimaryKey = shopInfoMapper.selectByPrimaryKey(shopInfoId);
		userInfoMapper.deleteByPrimaryKey(selectByPrimaryKey.getUserInfoId());
		shopInfoMapper.deleteByPrimaryKey(shopInfoId);
		map.put("state", 1);
		map.put("msg", "删除"+selectByPrimaryKey.getShopName()+"商户成功~");
		return map;
	}

	@Override
	public PageInfo<Map<String, Object>> getShopPage(int cur_page, int page_size, Map<String, Object> paramMap) {
		PageHelper.startPage(cur_page, page_size);
		List<Map<String, Object>> pageList = shopInfoMapper.getShopInfoPageList(paramMap);
		PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(pageList);
		return pageInfo;
	}

	@Override
	public void addShopOfMoney(Map<String, Object> paramMap) {
//		ShopAccount sa = shopAccountMapper.selectByPrimaryKey(Long.parseLong(paramMap.get("shopAccountId").toString()));
//		BigDecimal giveMoney = BigDecimal.valueOf(Long.parseLong(paramMap.get("giveMoney").toString()));
//		BigDecimal actualMoney = BigDecimal.valueOf(Long.parseLong(paramMap.get("actualMoney").toString()));
//		BigDecimal giveMoneyAndActualMoney = giveMoney.add(actualMoney);
//		BigDecimal aiscount = giveMoney.divide(giveMoneyAndActualMoney);
//		sa.setDiscount(aiscount.floatValue());
//		if(StringUtils.isEmpty(sa.getGiveMoney())) {
//			sa.setGiveMoney(giveMoney.add(BigDecimal.valueOf(Long.parseLong("0"))));
//		}else {
//			sa.setGiveMoney(giveMoney.add(sa.getGiveMoney()));
//		}
//		if(StringUtils.isEmpty(sa.getActualMoney())) {
//			sa.setActualMoney(actualMoney.add(BigDecimal.valueOf(Long.parseLong("0"))));
//		}else {
//			sa.setActualMoney(actualMoney.add(sa.getActualMoney()));
//		}
//		if(StringUtils.isEmpty(sa.getShopAccountMoney())) {
//			sa.setShopAccountMoney(giveMoneyAndActualMoney.add(BigDecimal.valueOf(Long.parseLong("0"))));
//		}else {
//			sa.setShopAccountMoney(giveMoneyAndActualMoney.add(sa.getShopAccountMoney()));
//		}
//		shopAccountMapper.updateByPrimaryKeySelective(sa);
		TransactionRecord tr = new TransactionRecord();
		tr.setComment(paramMap.get("shopName").toString()+"店铺充值");
		tr.setShopName(paramMap.get("shopName").toString());
		tr.setCreateDate(new Date());
		tr.setShopInfoId(Long.parseLong(paramMap.get("shopInfoId").toString()));
		tr.setMoney(paramMap.get("actualMoney").toString());
		tr.setTransactionType(1);
		tr.setAttr2(paramMap.get("giveMoney").toString());
		transactionRecordMapper.insertSelective(tr);
		try{
			Long userInfoId=Long.parseLong(paramMap.get("userInfoId").toString());
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String getTokenUrl=CommonUtil.getPropertiesParam("getTokenUrl");
			Map<String,String> getTokenParamMap=new HashMap<String,String>();
			getTokenParamMap.put("grant_type", CommonUtil.getPropertiesParam("grant_type"));
			getTokenParamMap.put("appid", CommonUtil.getPropertiesParam("wxgzhAppId"));
			getTokenParamMap.put("secret", CommonUtil.getPropertiesParam("wxgzhAppsecret"));
			String getTokenJson=HttpClientUtil.doGet(getTokenUrl, getTokenParamMap);
			String access_token=JsonUtils.fromJson(getTokenJson).get("access_token").asText();
			UserInfo userInfo=userInfoMapper.selectByPrimaryKey(userInfoId);

			//发送模板消息
			String sendTemplateUrl=CommonUtil.getPropertiesParam("sendTemplateUrl");
			Map<String,Object> sendTemplateMap=new HashMap<String,Object>();
			Map<String, Object> sendTemplateDataMap = new HashMap<String, Object>();
			Map<String, String> firstMap=new HashMap<String,String>();
			firstMap.put("value", tr.getComment());
			sendTemplateDataMap.put("first", firstMap);
			Map<String, String> keywordMap1=new HashMap<String,String>();
			keywordMap1.put("value", sdf.format(new Date()));
			sendTemplateDataMap.put("keyword1", keywordMap1);
			Map<String, String> keywordMap2=new HashMap<String,String>();
			keywordMap2.put("value", paramMap.get("actualMoney")+"元");
			sendTemplateDataMap.put("keyword2", keywordMap2);
			sendTemplateMap.put("touser", userInfo.getAttr1());
			sendTemplateMap.put("template_id", CommonUtil.getPropertiesParam("template_id"));
			Map<String, String> miniprogramMap=new HashMap<String,String>();
			miniprogramMap.put("appid", CommonUtil.getPropertiesParam("appid"));
			miniprogramMap.put("pagepath", CommonUtil.getPropertiesParam("sendTemplatePage"));
			sendTemplateMap.put("miniprogram", miniprogramMap);
			sendTemplateMap.put("data", sendTemplateDataMap);
			HttpClientUtil.doPostJson(sendTemplateUrl+"?access_token="+access_token, JsonUtils.toJson(sendTemplateMap));
		}catch(Exception e){
			logger.error("模板推送错误", e);
		}


	}

	@Override
	public Map<String, Object> getSelectShopNameAndTitle(Map<String, Object> paramMap) {
		Map<String, Object> retMap=new HashMap<String, Object>();
		retMap.put("shopNameList", shopInfoMapper.findSelectShopName(paramMap));
		retMap.put("shopTitleList", classifyInfoMapper.findSelectTitle(paramMap.get("paramStr").toString()));
		return retMap;
	}

	@Override
	public void settlementShopMoney(Map<String, Object> paramMap) {
//		ShopAccount sa = shopAccountMapper.selectByPrimaryKey(Long.parseLong(paramMap.get("shopAccountId").toString()));
//		BigDecimal actualMoney = BigDecimal.valueOf(Long.parseLong(paramMap.get("actualMoney").toString()));
//		if(StringUtils.isEmpty(sa.getActualMoney())) {
//			sa.setActualMoney(actualMoney.add(BigDecimal.valueOf(Long.parseLong("0"))));
//		}else {
//			sa.setActualMoney(actualMoney.add(sa.getActualMoney()));
//		}
//		if(StringUtils.isEmpty(sa.getShopAccountMoney())) {
//			sa.setShopAccountMoney(actualMoney);
//		}else {
//			sa.setShopAccountMoney(actualMoney.add(sa.getShopAccountMoney()));
//		}
//		shopAccountMapper.updateByPrimaryKeySelective(sa);
		TransactionRecord tr = new TransactionRecord();
		tr.setComment(paramMap.get("shopName").toString()+"店铺结算");
		tr.setShopName(paramMap.get("shopName").toString());
		tr.setCreateDate(new Date());
		tr.setShopInfoId(Long.parseLong(paramMap.get("shopInfoId").toString()));
		tr.setMoney(paramMap.get("actualMoney").toString());
		tr.setAttr2(paramMap.get("actualHandingOver").toString());
		tr.setTransactionType(2);
		transactionRecordMapper.insertSelective(tr);
		try{
			Long userInfoId=Long.parseLong(paramMap.get("userInfoId").toString());
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String getTokenUrl=CommonUtil.getPropertiesParam("getTokenUrl");
			Map<String,String> getTokenParamMap=new HashMap<String,String>();
			getTokenParamMap.put("grant_type", CommonUtil.getPropertiesParam("grant_type"));
			getTokenParamMap.put("appid", CommonUtil.getPropertiesParam("wxgzhAppId"));
			getTokenParamMap.put("secret", CommonUtil.getPropertiesParam("wxgzhAppsecret"));
			String getTokenJson=HttpClientUtil.doGet(getTokenUrl, getTokenParamMap);
			String access_token=JsonUtils.fromJson(getTokenJson).get("access_token").asText();
			UserInfo userInfo=userInfoMapper.selectByPrimaryKey(userInfoId);

			//发送模板消息
			String sendTemplateUrl=CommonUtil.getPropertiesParam("sendTemplateUrl");
			Map<String,Object> sendTemplateMap=new HashMap<String,Object>();
			Map<String, Object> sendTemplateDataMap = new HashMap<String, Object>();
			Map<String, String> firstMap=new HashMap<String,String>();
			firstMap.put("value", tr.getComment());
			sendTemplateDataMap.put("first", firstMap);
			Map<String, String> keywordMap1=new HashMap<String,String>();
			keywordMap1.put("value", sdf.format(new Date()));
			sendTemplateDataMap.put("keyword1", keywordMap1);
			Map<String, String> keywordMap2=new HashMap<String,String>();
			keywordMap2.put("value", paramMap.get("actualMoney")+"元");
			sendTemplateDataMap.put("keyword2", keywordMap2);
			sendTemplateMap.put("touser", userInfo.getAttr1());
			sendTemplateMap.put("template_id", CommonUtil.getPropertiesParam("template_id"));
			Map<String, String> miniprogramMap=new HashMap<String,String>();
			miniprogramMap.put("appid", CommonUtil.getPropertiesParam("appid"));
			miniprogramMap.put("pagepath", CommonUtil.getPropertiesParam("sendTemplatePage"));
			sendTemplateMap.put("miniprogram", miniprogramMap);

			sendTemplateMap.put("data", sendTemplateDataMap);
			HttpClientUtil.doPostJson(sendTemplateUrl+"?access_token="+access_token, JsonUtils.toJson(sendTemplateMap));
		}catch(Exception e){
			logger.error("模板推送错误", e);
		}
	}

	@Override
	public Map<String, Object> updShopInfo(Map<String, Object> paramMap) {
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			ShopInfoWithBLOBs shopInfo = shopInfoMapper.selectByPrimaryKey(Long.parseLong(paramMap.get("shopInfoId").toString()));
			shopInfo.setAttr2(paramMap.get("attr2").toString());
			shopInfo.setBusinessPermitPhoto(paramMap.get("businessPermitPhoto").toString());
			shopInfo.setLatitude(paramMap.get("latitude").toString());
			shopInfo.setLongitude(paramMap.get("longitude").toString());
			shopInfo.setTelephone(paramMap.get("telephone").toString());
			shopInfo.setBusinessDate(paramMap.get("businessDate").toString());
			shopInfo.setShopType(paramMap.get("shopType").toString());
			shopInfo.setShopTitle(paramMap.get("shopTitle").toString());
			shopInfo.setShopName(paramMap.get("shopName").toString());
			shopInfo.setShopComment(paramMap.get("shopComment").toString());
			shopInfo.setAttr1(paramMap.get("attr1").toString());
			shopInfo.setAttr3(paramMap.get("attr3").toString());
			if(!StringUtils.isEmpty(paramMap.get("headName").toString())) {
				shopInfo.setHeadName(paramMap.get("headName").toString());
			}
			if(!StringUtils.isEmpty(paramMap.get("headPhone").toString())) {
				shopInfo.setHeadPhone(paramMap.get("headPhone").toString());
			}
			shopInfo.setProvince(paramMap.get("province").toString());
			shopInfo.setCity(paramMap.get("city").toString());
			shopInfo.setDistrict(paramMap.get("district").toString());
//			int loginNameCount = userInfoMapper.getLoginNameCount(paramMap.get("userPhone").toString());
//			if(loginNameCount>0) {
//				map.put("state", 2);
//				map.put("msg", "手机号已被注册~");
//			}else {
				UserInfo ui = new UserInfo();
				ui.setMobile(shopInfo.getTelephone());
				ui.setUserState(1);
				ui.setUserInfoId(shopInfo.getUserInfoId());
				ui.setCertificateCode(paramMap.get("certificateCode").toString());
				userInfoMapper.updateByPrimaryKeySelective(ui);
				shopInfo.setShopState(1);
				shopInfoMapper.updateByPrimaryKeyWithBLOBs(shopInfo);
				ShopAccount sa = shopAccountMapper.selectByPrimaryKey(Long.parseLong(paramMap.get("shopAccountId").toString()));
				sa.setDiscount(Float.valueOf(paramMap.get("discount").toString()));
				shopAccountMapper.updateByPrimaryKey(sa);
				map.put("state", 1);
				map.put("msg", "编辑成功~");
//			}
		}catch(Exception e) {
			map.put("state", -1);
			map.put("msg", "系统崩溃了,请稍后再尝试~");
			e.printStackTrace();
		}
		return map;
	}

}
